package com.zhny.aiot.solar.roll.film.plugin;

import com.google.common.collect.ImmutableMap;
import com.zhny.aiot.plugin.ICenterFacilities;
import com.zhny.aiot.plugin.IDeviceFactory;
import com.zhny.aiot.plugin.core.utils.MessageUtils;
import com.zhny.aiot.plugin.model.DeviceEntity;
import com.zhny.aiot.plugin.model.MessageEntry;
import com.zhny.aiot.plugin.model.MessageType;
import com.zhny.aiot.plugin.model.TaskEntity;
import com.zhny.aiot.plugin.zhnygateway.GatewayEngine;
import com.zhny.aiot.plugin.zhnygateway.device.ZhnyConfig;
import com.zhny.aiot.plugin.zhnygateway.device.ZhnyDevice;
import com.zhny.aiot.plugin.zhnygateway.model.GatewayResponseMessage;
import com.zhny.aiot.plugin.zhnygateway.model.NodeRequestMessage;
import com.zhny.aiot.solar.roll.film.plugin.model.RollFilmStoreEntry;
import org.pf4j.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class SolarRollFilmDevice extends ZhnyDevice<RollFilmStoreEntry> {
    private static final Logger logger = LoggerFactory.getLogger(SolarRollFilmDevice.class);
    private final Map<String, Integer> CommandOperations;
    public SolarRollFilmDevice(GatewayEngine engine, IDeviceFactory<ZhnyConfig> factory, ICenterFacilities centerFacilities, DeviceEntity entity) {
        super (engine, factory, centerFacilities, entity);
        CommandOperations =  new ImmutableMap.Builder<String, Integer>()
                .put("open", 0x31)
                .put("close", 0x32)
                .put("stop", 0x30)
                .put("query", 0x39)
                .put("queryVoltage", 0x3A).build();
    }

    @Override
    public void onDecoder(GatewayResponseMessage message) {
        logger.info (message.toString ());
        int type = message.getDeviceType ();
        if(type == 0x11){
            logger.info("---start decoder solar roll film valve message---");
            onMessage(message);
        }
    }

    private void onMessage(GatewayResponseMessage message) {
        MessageEntry resultMsg = MessageUtils.createMessageEntry (this.getId ());
        resultMsg.setType(MessageType.RESULT);
        RollFilmStoreEntry storeEntry = new RollFilmStoreEntry ();
        int operation = message.getDeviceOper ();
        logger.info ("--- solar roll film current operation {}---",operation);
        if(operation >= 0x30 && operation <= 0x32){
            if(message.getDataLength () == 7){
                resultMsg.setType (MessageType.ERROR);
                resultMsg.setData ("水利机械阀加入任务失败");
                logger.error ("[deviceNo:{},controllerNo:{}] 水利机械阀加入任务[{}]失败"
                        , getConfig ().getAddress (), getConfig ().getChannelNo (), operation);
                nofity (resultMsg);
                return;
            }else if(operation == 0x30) {
                int volValue = message.getDeviceData ().readUnsignedShort ();
                int status = message.getDeviceData ().readUnsignedShort ();
                storeEntry.setVoltage (createVol (volValue));
                storeEntry.setRollFilmStatus ("停止");
            }
            else if(operation == 0x31){
                int volValue = message.getDeviceData ().readUnsignedShort ();
                int status = message.getDeviceData ().readUnsignedShort ();
                storeEntry.setVoltage (createVol (volValue));
                storeEntry.setRollFilmStatus ("开");
            } else if(operation == 0x32){
                int volValue = message.getDeviceData ().readUnsignedShort ();
                int status = message.getDeviceData ().readUnsignedShort ();
                storeEntry.setVoltage (createVol (volValue));
                storeEntry.setRollFilmStatus ("关");
            }
        } else if(operation == 0x39) {
            int volValue = message.getDeviceData ().readUnsignedShort ();
            int status = message.getDeviceData ().readByte ();
            String isOpenStatus = status== 1?"开":status==0?"关":"停止";
            Boolean isSotateStatus = message.getDeviceData ().readByte () == 1?true:false;
            storeEntry.setVoltage (createVol (volValue));
            storeEntry.setRollFilmStatus (isOpenStatus);
        }else if(operation == 0x3A){
            storeEntry.setVoltage (createVol(message.getDeviceData ().readShort ()));
        }
        resultMsg.setData (storeEntry);

        logger.info("solar roll film store[{}]",storeEntry.toString());
        save (storeEntry);
        saveReal (storeEntry);
        nofity (resultMsg);
    }

    private double createVol(int vol){
        double result = ((vol / 4096.00)*3.30*74.00)/12.00;
        return Double.parseDouble(String.format("%.2f",result));
    }

    @Override
    protected NodeRequestMessage onCommand(TaskEntity taskEntity) {
        if(StringUtils.isNullOrEmpty (taskEntity.getMethodName ()))
            return null;

        Map<String,Object> command =new HashMap<> ();
        command.put (taskEntity.getMethodName (),null);
        logger.info ("config address[{}]",Integer.parseInt (getConfig ().getAddress ()));
        return encode (command);
    }

    private NodeRequestMessage encode(Map<String, Object> commandMap) {
        for (String id : commandMap.keySet ()){
            if(CommandOperations.containsKey (id)) {
                Integer oper=CommandOperations.get (id);
                int length=4;
                return new NodeRequestMessage (getzhnyType ()+128, length, oper, Integer.parseInt (getConfig ().getAddress ()), null);
            }
        }
        return null;
    }

    @Override
    protected int getzhnyType() {
        return 17;
    }

    @Override
    protected void disposable() {

    }
}
